var t1;
$(function () {
    $.ajax({
        type: 'POST',
        url: '/enable/getOppenMerchantMsg',
        async: false,
        data: {},
        dataType: 'json',
        success: function (result) {
            if (result.code==666){
                var merchantCount = result.data.merchantList.length;
                var count = 0;
                if (merchantCount>0){
                for (i = 0;i<merchantCount;i++) {
                   $("#able-merchant").append("<div class='able-a-merchant'><a class='able-a-merchant ' onclick='rechargeMerchant(this,"+result.data.merchantList[i].id+");'>"+result.data.merchantList[i].name+"</a></div>");
                    }
                if (count==0) {
                    roadRecharge(result.data.merchantList[0].name,result.data.merchantList[0].id);count++;
                }
                }
            }else{
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest.status);
            if (XMLHttpRequest.status==555){
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                        top.location.href="/login";
                    });
                });
            }else{
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('页面加载失败',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                    });
                });
            }
        },
    });
});
function rechargeMerchant(obj,id) {
    $.ajax({
        type: 'POST',
        url: '/recharge/rechargeDetail',
        async: false,
        data: {"merchantId":id},
        dataType: 'json',
        success: function (result) {
            if (result.code==666){
            console.log(result.data);
            if (obj!=null){
                $(".uppercase").text($(obj).text());
                $("#rechargecompany").text($(obj).text());
            }else{
                $(".uppercase").text(result.data.recharge.merchantname);
                $("#rechargecompany").text($(obj).text());
            }

                $("#state").text("正常");
                $("#merchant_id").val(result.data.recharge.merchantid);
                $("#balance").text(result.data.recharge.afterrecharge)
                $("#recordtime").text(formatDate(result.data.recharge.recordtime));
                $("#rechargeamount").text(result.data.recharge.rechargeamount)

            }else{
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status==555){
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                        top.location.href="/login";
                    });
                });
            }else{
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('页面加载失败',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                    });
                });
            }
        },
    });
}
function formatDate(timestamp) {
    if (timestamp) {
        var time = new Date(timestamp*1000);
        var y = time.getFullYear();
        var M = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var m = time.getMinutes();
        var s = time.getSeconds();
        return y + '-' + addZero(M) + '-' + addZero(d) + ' ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s);
    } else {
        return '';
    }
}
function addZero(m) {
    return m < 10 ? '0' + m : m;
}
$("#recharge").click(function () {

    var Channel = $('#channel_type input:radio:checked').val();
    var recharge = $("input[name='recharge']").val();
    var beforerecharge = $("#balance").text();
    var merchant_id =   $("#merchant_id").val();
    var merchantname = $(".uppercase").text();
    var msgStr = '您将为' + merchantname + '充值' + recharge + '元';
    var timestamp = (new Date()).getTime();
    if (!checkRate(recharge)){
        var layer;
        layui.use(['layer', 'form'], function(){
            layer = layui.layer
        });
        layer.msg('请输入正确格式的充值金额', {icon: 2,time:2000});
    }else {
        if (merchant_id != null && merchant_id != "") {
            layui.use(['layer', 'form'], function () {
                layer = layui.layer;
                layer.confirm(msgStr, {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    layer.close(layer.index);
                    if (Channel == 1) {
                        $.ajax({
                            type: 'POST',
                            url: '/recharge/recharge',
                            async: false,
                            data: {
                                "channel": Channel,
                                "rechargeamount": recharge,
                                "beforerecharge": beforerecharge,
                                "merchantid": merchant_id,
                                "merchantname": merchantname
                            },
                            dataType: 'json',
                            success: function (result) {
                                if (result.code == 666) {
                                    console.log(result.data)
                                    $('.re').css('display', 'none');
                                    $('.re2').css('display', 'block');
                                    $(".serialnumber").text(result.data.recharge.id);
                                    $(".name").text(merchantname);
                                    $(".phone1").text(result.data.merchant.phone1);
                                    $(".recordtime").text(formatDate(result.data.recharge.recordtime));
                                    $(".companyname2").text(result.data.companyName);
                                    if (result.data.recharge.channel == 1) {
                                        $('.channel').text('现金');
                                    } else if (result.data.recharge.channel == 2) {
                                        $('.channel').text('微信');
                                    } else if (result.data.recharge.channel == 3) {
                                        $('.channel').text('支付宝');
                                    }
                                    $('.rechargeamount').text(result.data.recharge.rechargeamount);
                                    $('.beforerecharge').text(result.data.recharge.beforerecharge);
                                    $('.afterrecharge').text(result.data.recharge.afterrecharge);
                                    $('.wallet').text('预付费子账户钱包');
                                } else {
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                if (XMLHttpRequest.status == 555) {
                                    var layer;
                                    layui.use(['layer', 'form'], function () {
                                        layer = layui.layer
                                        layer.alert('未登录,请登录后操作', {icon: 7}, function (index) {
                                            //do something
                                            layer.close(index);
                                            top.location.href = "/login";
                                        });
                                    });
                                } else {
                                    var layer;
                                    layui.use(['layer', 'form'], function () {
                                        layer = layui.layer
                                        layer.alert('页面加载失败', {icon: 7}, function (index) {
                                            //do something
                                            layer.close(index);
                                        });
                                    });
                                }
                            },
                        });
                    } else if (Channel == 2) {
                        //打开付费二维码 -- 微信二维码
                        layer.open({
                            area: ['300px', '300px'],
                            type: 2,
                            closeBtn: false,
                            title: false,
                            shift: 2,
                            shadeClose: true,
                            content: '/recharge/qrcode?merchantId=' + merchant_id + '&rechargeamount=' + recharge + '&timestamp=' + timestamp
                        });
                        var orderStr = merchant_id + "-" + timestamp;
                        //重复执行某个方法
                        t1 = window.setInterval("getPayState('" + orderStr + "')", 1500);
                    } else if (Channel == 3) {
                        $.ajax({
                            type: 'POST',
                            url: '/recharge/goAlipay',
                            async: false,
                            data: {"merchantId": merchant_id, "rechargeamount": recharge, "timestamp": timestamp},
                            dataType: 'json',
                            success: function (result) {
                                // 添加之前先删除一下，如果单页面，页面不刷新，添加进去的内容会一直保留在页面中，二次调用form表单会出错
                                let divForm = document.getElementsByTagName('divform');
                                if (divForm.length) {
                                    document.body.removeChild(divForm[0])
                                }
                                const div = document.createElement('divform');
                                div.innerHTML = result; // data就是接口返回的form 表单字符串
                                document.body.appendChild(div);
                                document.forms[0].setAttribute('target', '_blank') // 新开窗口跳转
                                document.forms[0].submit();

                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {

                            }
                        });
                        //loading层
                        var loadingIndex = layer.load(0, { //icon支持传入0-2
                            shade: [0.5, 'white'], //0.5透明度的灰色背景
                            content: '支付中...',
                            success: function (layero) {
                                layero.find('.layui-layer-content').css({
                                    'padding-top': '40px',
                                    'width': '100px',
                                    'font-size': '18px'
                                });
                            }
                        });
                        var orderStr = merchant_id + "-" + timestamp;
                        //重复执行某个方法
                        t1 = window.setInterval("getPayState('" + orderStr + "')", 1500);
                    } else {
                        layer.alert('请选择充值方式', {icon: 7}, function (index) {
                            //do something
                            layer.close(index);
                        });
                    }
                }, function () {
                });
            });
        } else {
            var layer;
            layui.use(['layer', 'form'], function () {
                layer = layui.layer
                layer.alert('请先选择充值账户', {icon: 7}, function (index) {
                    //do something
                    layer.close(index);
                });
            });
        }
    }
});

function numChange() {

    if (checkRate($("#out").val())||$("#out").val()=="") {
        $("#rechargenum").text($("#out").val());
    }else{
        $("#rechargenum").text("");
        /*var layer;
        layui.use(['layer', 'form'], function(){
            layer = layui.layer
            layer.alert('输入正确的充值金额',{icon:2}, function(index){
                //do something
                layer.close(index);
            });
        });*/
    }
}

function checkRate(nubmer) {

    var pattern = /^[0-9]*[.]+[0-9]{1,2}$|^[0-9]+$/
    if (!pattern.test(nubmer)) {
        return false;
    }else{
        return true;
    }
}
function roadRecharge(namestr,id) {
    $.ajax({
        type: 'POST',
        url: '/recharge/rechargeDetail',
        async: false,
        data: {"merchantId":id},
        dataType: 'json',
        success: function (result) {
            if (result.code==666){
                $(".uppercase").text(namestr);
                $("#state").text("正常");
                $("#merchant_id").val(result.data.recharge.merchantid);
                $("#balance").text(result.data.recharge.afterrecharge);
                $("#recordtime").text(formatDate(result.data.recharge.recordtime));
                $("#rechargeamount").text(result.data.recharge.rechargeamount)

            }else{
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status==555){
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                        top.location.href="/login";
                    });
                });
            }else{
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('页面加载失败',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                    });
                });
            }
        },
    });
}
$('#ad').click(function () {
    window.location.reload()
});
//表格导出
function exportTable() {
    // 获取头部和body
    var data = LAY_EXCEL.tableToJson(document.getElementById('print-content')) // 或者 $('#LAY-EXPORT-TEST')
    // console.log(data)
    var exportData = []
    exportData.push.apply(exportData, data.head)
    exportData.push.apply(exportData, data.body)
    // console.log(exportData)

    LAY_EXCEL.exportExcel(exportData, '充值收据.xlsx', 'xlsx')
}
//打印
function printout() {
    debugger;
    var newWindow;
    //打开一个新的窗口
    newWindow = window.open();
    // 是新窗口获得焦点
    newWindow.focus();
    //保存写入内容
    var newContent = "";
    newContent += document.getElementById("print-content").outerHTML;
    newContent += "</body></html>";
    // 将HTML代码写入新窗口中
    newWindow.document.write(newContent);
    newWindow.print();
    // close layout stream
    newWindow.document.close();
    //关闭打开的临时窗口
    newWindow.close();
    return false;
};
function getPayState(orderStr){
    var layer;
    layui.use(['layer', 'form'], function(){
        layer = layui.layer}
        );
    //轮询是否已经付费
    $.ajax({
        type:'post',
        url:"/recharge/hadPay",
        data:{"orderStr":orderStr},
        cache:false,
        async:true,
        dataType: 'json',
        success:function(result){
            if (result.code==666){
                layer.close(layer.index);
                clearInterval(t1);
               $('.re').css('display', 'none');
                $('.re2').css('display', 'block');
                $(".serialnumber").text(result.data.recharge.id);
                $(".name").text(result.data.recharge.merchantname);
                $(".phone1").text(result.data.merchant.phone1);
                $(".recordtime").text(formatDate(result.data.recharge.recordtime));
                $(".companyname2").text(result.data.companyName);
                if (result.data.recharge.channel == 1) {
                    $('.channel').text('现金');
                } else if (result.data.recharge.channel == 2) {
                    $('.channel').text('微信');
                } else if (result.data.recharge.channel == 3) {
                    $('.channel').text('支付宝');
                }
                $('.rechargeamount').text(result.data.recharge.rechargeamount);
                $('.beforerecharge').text(result.data.recharge.beforerecharge);
                $('.afterrecharge').text(result.data.recharge.afterrecharge);
                $('.wallet').text('预付费子账户钱包');

            }else{

            }
        },
        error:function(){
        }
    });
}
